#include "./FTcpExample.h"

#include "Sockets.h"
#include "SocketSubsystem.h"

FTcpExample::FTcpExample()
{
	bIsReceiving = false;
	NativeSocket = nullptr;
	ListenThread = nullptr;
}

FTcpExample::~FTcpExample()
{
	Abort();
}

bool FTcpExample::Connect(const FString& IP, const int32 Port)
{
	auto InternetAddr = ISocketSubsystem::Get(PLATFORM_SOCKETSUBSYSTEM)->CreateInternetAddr();
	bool IsValid = false;
	InternetAddr->SetIp(*IP, IsValid);
	if (!IsValid)
	{
		UE_LOG(LogTemp, Warning, TEXT("%s 当前地址格式不正确！"), *IP);
		return false;
	}
	InternetAddr->SetPort(Port);
	NativeSocket = ISocketSubsystem::Get(PLATFORM_SOCKETSUBSYSTEM)->CreateSocket(NAME_Stream, TEXT("FTcp Example"));
	return NativeSocket->Connect(*InternetAddr);
}

void FTcpExample::StartListen()
{
	bIsReceiving = true;
	ListenThread = FRunnableThread::Create(this, TEXT("FTcpExample Thread"));
}


uint32 FTcpExample::Run()
{
	if (NativeSocket)
	{
		uint8* Buffer = new uint8[TCP_BUFFER_SIZE];
		int32 ReadSize;
		while (bIsReceiving)
		{
			NativeSocket->Recv(Buffer, TCP_BUFFER_SIZE, ReadSize);
			if (ReadSize > 0)
			{
				FUTF8ToTCHAR UTC(reinterpret_cast<const ANSICHAR*>(Buffer), ReadSize);
				FString Msg(UTC.Length(), UTC.Get());
				UE_LOG(LogTemp, Warning, TEXT("接收到 TCP 消息：%s"), *Msg);
			}
			else
				Abort();
		}
	}
	return 0;
}

void FTcpExample::Abort()
{
	UE_LOG(LogTemp, Warning, TEXT("终止 TCP 连接！！！"));
	if (!bIsReceiving) return;
	bIsReceiving = false;
	if (NativeSocket)
	{
		NativeSocket->Close();
		ISocketSubsystem::Get(PLATFORM_SOCKETSUBSYSTEM)->DestroySocket(NativeSocket);
		NativeSocket = nullptr;
	}
	if (ListenThread)
	{
		ListenThread->Kill();
		delete ListenThread;
		ListenThread = nullptr;
	}
}

void FTcpExample::Close()
{
	Abort();
}

void FTcpExample::SendMsg(const FString& Msg) const
{
	if (!NativeSocket) return;
	FTCHARToUTF8 Data(*Msg, Msg.Len());
	TArray<uint8> Buffer;
	Buffer.Append(reinterpret_cast<const uint8*>(Data.Get()), Data.Length());
	int32 WriteSize;
	NativeSocket->Send(Buffer.GetData(), Buffer.Num(), WriteSize);
}
 